package com.clkj.goldpartner.controller;

import com.alibaba.fastjson.JSON;
import com.clkj.goldpartner.pojo.*;
import com.clkj.goldpartner.pojo.common.*;
import com.clkj.goldpartner.service.SystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * @author 杨行
 * @date 2021/2/28 16:33
 */

@RestController
@RequestMapping(value = "/system")
@CrossOrigin //跨域
@Api(value = "/api", tags = {"系统设置"})
public class SystemController {
    @Autowired
    private SystemService systemService;

    private Map map;

    public static String addFlag = "add";

    public static String unableFlag = "0";

    /**
     * 关闭门店
     *
     * @param shop_id
     */
    @PostMapping("/updateShop")
    public Result updateShop(@RequestParam("shop_id") Integer shop_id) {
        try {
            systemService.updateShop(shop_id);
            return new Result(true, StatusCode.OK, "关闭成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "关闭失败");
        }
    }

    /**
     * 获取门店列表
     */
    @PostMapping("/getShop")
    public Result getShop() {
        try {
            List<Shop> shops = systemService.getShop();
            return new Result(true, StatusCode.OK, "获取成功", shops);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "获取失败");
        }
    }

    /**
     * 获取门店列表
     */
    @PostMapping("/getShopAndChildren")
    public Result getShopAndChildren() {
        try {
            List<Shop> shops = systemService.getShopAndChildren();
            return new Result(true, StatusCode.OK, "获取成功", shops);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "获取失败");
        }
    }

    /**
     * 添加门店
     *
     * @param shop
     */
    @PostMapping("/addShop")
    public Result addShop(Shop shop, HttpServletRequest request) {
        try {
            if (shop.getParent_id() == null) {
                shop.setParent_id(0);
            }
            shop.setShop_status("1");
            shop.setCreate_time(DateFormatHelper.currentTimes());
//            String ip =GetMacAddress.getIpAddr(request);
//            GetMacAddress  uMac = new GetMacAddress();
//            String sMac = uMac.getMacAddress(ip);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            Long time = System.currentTimeMillis();
            shop.setShop_account(time.toString().substring(time.toString().length() - 6));
            shop.setShop_note(uuid);
            systemService.addShop(shop);
            return new Result(true, StatusCode.OK, "添加成功", uuid);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "添加失败");
        }
    }

    @PostMapping("/login")
    public Result login(@RequestParam("account") String account, @RequestParam("password") String password, @RequestParam("uuid") String uuid, HttpServletResponse response) {
        try {
            Shop shop = systemService.getShopByAccount(account);
            if (shop == null) {
                return new Result(false, StatusCode.ERROR, "登录失败，账号或密码错误", "登录失败，账号或密码错误");
            }
            if (unableFlag.equals(shop.getShop_status())) {
                return new Result(false, StatusCode.ERROR, "登录失败，该用户已被禁用", "登录失败，该用户已被禁用");
            }
            if (shop.getShop_password().equals(password)) {
                if (shop.getShop_id() != -15114561) {
//                    String ip =GetMacAddress.getIpAddr(request);
//                    GetMacAddress  uMac = new GetMacAddress();
//                    String sMac = uMac.getMacAddress(ip);
//                    if(!sMac.equals(shop.getShop_note())){
//                        return new Result(false, StatusCode.ERROR,"登录失败，该账户与绑定的电脑(主机)不匹配，请在指定电脑访问","登录失败，该账户与绑定的电脑(主机)不匹配，请在指定电脑访问");
//                    }
                    if (!uuid.equals(shop.getShop_note())) {
                        return new Result(false, StatusCode.ERROR, "登录失败，该账户与绑定的电脑(主机)不匹配，请在指定电脑访问", "登录失败，该账户与绑定的电脑(主机)不匹配，请在指定电脑访问");
                    }
                }
                //创建用户令牌信息
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("userName", shop.getUserName());
                map.put("shop_name", shop.getShop_name());
                map.put("shop_id", shop.getShop_id());
                String token = JwtUtil.createJwt(UUID.randomUUID().toString(), JSON.toJSONString(map), null);
                shop.setShop_note(token);
                //把令牌信息存入Cookie中
                Cookie cookie = new Cookie("Authorization", token);
                cookie.setPath("/");
                cookie.setDomain("localhost");
                response.addCookie(cookie);
                //把令牌作为参数传给用户
                return new Result(true, StatusCode.OK, "登录成功", shop);
            } else {
                return new Result(false, StatusCode.ERROR, "登录失败，账号或密码错误", "登录失败，账号或密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "登录失败", "登录失败");
        }
    }

    /**
     * 获取人员管理列表
     *
     * @param shop_id
     * @param member_name
     * @param member_sex
     * @return Result
     */
    @PostMapping("getMemberList")
    @ApiOperation(value = "获取人员管理列表")
    public Result getMemberList(@RequestParam("shop_id") Integer shop_id, @RequestParam("member_name") String member_name, @RequestParam("member_sex") String member_sex) {
        try {
            List<Member> members = systemService.getMemberList(shop_id, member_name, member_sex);
            return new Result(true, StatusCode.OK, "获取成功", members);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "获取失败");
        }
    }

    /**
     * 获取相关分类人员列表
     *
     * @param shop_id
     * @param member_type
     * @return Result
     */
    @PostMapping("getMemberListByType")
    @ApiOperation(value = "获取相关分类人员列表")
    public Result getMemberListByType(@RequestParam("shop_id") Integer shop_id, @RequestParam("member_type") String member_type) {
        try {
            List<Member> members = systemService.getMemberListByType(shop_id, member_type);
            return new Result(true, StatusCode.OK, "获取成功", members);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "获取失败");
        }
    }

    /**
     * 添加人员
     *
     * @param member
     * @param flag
     * @return Result
     */
    @PostMapping("addMember")
    @ApiOperation(value = "添加人员")
    public Result addMember(Member member, @RequestParam("flag") String flag) {
        try {
            if (addFlag.equals(flag)) {
                member.setMember_status("0");
                systemService.addMember(member);
            } else {
                systemService.editMember(member);
            }
            return new Result(true, StatusCode.OK, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "添加失败");
        }
    }

    /**
     * 删除人员
     *
     * @param ids
     * @return Result
     */
    @PostMapping("deleteMember")
    @ApiOperation(value = "删除人员")
    public Result deleteMember(@RequestParam("ids") String ids) {
        try {
            systemService.deleteMember(ids);
            return new Result(true, StatusCode.OK, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "删除失败");
        }
    }


    /**
     * 新增供货商
     *
     * @param supplier
     * @param flag
     * @return Result
     */
    @PostMapping("addSupplier")
    @ApiOperation(value = "新增供货商")
    public Result addSupplier(Supplier supplier, HttpServletRequest request, @RequestParam("flag") String flag) {
        try {
            MultipartFile file = ((MultipartRequest) request).getFile("file");
            MultipartFile file1 = ((MultipartRequest) request).getFile("file1");
            MultipartFile file2 = ((MultipartRequest) request).getFile("file2");
            if (file != null) {
                String fileName = FileUploadTool.upload(request, file, "supplier", "D:\\apache-tomcat-8.5.37\\webapps\\zhibanzhang\\resource\\goldpartner");
                supplier.setLicence_pic(fileName);
            }
            if (file1 != null) {
                String fileName = FileUploadTool.upload(request, file1, "supplier", "D:\\apache-tomcat-8.5.37\\webapps\\zhibanzhang\\resource\\goldpartner");
                supplier.setBusLicence_pic(fileName);
            }
            if (file2 != null) {
                String fileName = FileUploadTool.upload(request, file2, "supplier", "D:\\apache-tomcat-8.5.37\\webapps\\zhibanzhang\\resource\\goldpartner");
                supplier.setGMP_pic(fileName);
            }
            if (addFlag.equals(flag)) {
                String supplier_num = systemService.getSupplier_num();
                Integer id = 0;
                if (supplier_num != null) {
                    id = Integer.parseInt(supplier_num) + 1;
                } else {
                    id = 1;
                }
                supplier_num = String.format("%08d", id);
                supplier.setSupplier_num(supplier_num);
                supplier.setSupplier_status("0");
                supplier.setCreat_date(DateFormatHelper.currentTimes());
                systemService.addSupplier(supplier);
            } else {
                systemService.editSupplier(supplier);
            }
            return new Result(true, StatusCode.OK, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "添加失败");
        }
    }

    /**
     * 获取供货商
     *
     * @param shop_id
     * @param supplier_name
     * @param supplier_num
     * @return Result
     */
    @PostMapping("getSupplier")
    @ApiOperation(value = "获取供货商")
    public Result getSupplier(@RequestParam("shop_id") Integer shop_id, @RequestParam("supplier_name") String supplier_name, @RequestParam("supplier_num") String supplier_num) {
        try {
            List<Supplier> suppliers = systemService.getSupplier(shop_id, supplier_name, supplier_num);
            return new Result(true, StatusCode.OK, "获取成功", suppliers);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "获取失败");
        }
    }

    /**
     * 获取可用供货商
     *
     * @param shop_id
     * @param supplier_name
     * @param supplier_num
     * @return Result
     */
    @PostMapping("getSupplierNow")
    @ApiOperation(value = "获取可用供货商")
    public Result getSupplierNow(@RequestParam("shop_id") Integer shop_id, @RequestParam("supplier_name") String supplier_name, @RequestParam("supplier_num") String supplier_num) {
        try {
            List<Supplier> suppliers = systemService.getSupplierNow(shop_id, supplier_name, supplier_num);
            return new Result(true, StatusCode.OK, "获取成功", suppliers);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "获取失败");
        }
    }

    /**
     * 删除供货商
     *
     * @param ids
     * @return Result
     */
    @PostMapping("deleteSupplier")
    @ApiOperation(value = "删除供货商")
    public Result deleteSupplier(@RequestParam("ids") String ids) {
        try {
            systemService.deleteSupplier(ids);
            return new Result(true, StatusCode.OK, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "删除失败");
        }
    }


    /**
     * 获取客户列表
     *
     * @param shop_id
     * @param customer_name
     * @param customer_num
     * @return Result
     */
    @PostMapping("getCustomer")
    @ApiOperation(value = "获取客户列表")
    public Result getCustomer(@RequestParam("shop_id") Integer shop_id, @RequestParam("customer_name") String customer_name, @RequestParam("customer_num") String customer_num) {
        try {
            List<Customer> customers = systemService.getCustomer(shop_id, customer_name, customer_num);
            return new Result(true, StatusCode.OK, "获取成功", customers);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "获取失败");
        }
    }


    /**
     * 添加客户
     *
     * @param customer
     * @param flag
     * @return Result
     */
    @PostMapping("addCustomer")
    @ApiOperation(value = "添加客户")
    public Result addCustomer(HttpServletRequest request, Customer customer, @RequestParam("flag") String flag) {
        try {
            MultipartFile file = ((MultipartRequest) request).getFile("file");
            MultipartFile file1 = ((MultipartRequest) request).getFile("file1");
            if (file != null) {
                String fileName = FileUploadTool.upload(request, file, "customer", "D:\\apache-tomcat-8.5.37\\webapps\\zhibanzhang\\resource\\goldpartner");
                customer.setBusLicence_pic(fileName);
            }
            if (file1 != null) {
                String fileName = FileUploadTool.upload(request, file1, "customer", "D:\\apache-tomcat-8.5.37\\webapps\\zhibanzhang\\resource\\goldpartner");
                customer.setGMP_pic(fileName);
            }
            if (addFlag.equals(flag)) {
                String customer_num = systemService.getCustomer_num();
                Integer id = 0;
                if (customer_num != null) {
                    id = Integer.parseInt(customer_num) + 1;
                } else {
                    id = 1;
                }
                customer_num = String.format("%08d", id);
                customer.setCustomer_num(customer_num);
                customer.setCustomer_status("0");
                systemService.addCustomer(customer);
            } else {
                systemService.editCustomer(customer);
            }
            return new Result(true, StatusCode.OK, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "添加失败");
        }
    }


    /**
     * 删除客户列表
     *
     * @param ids
     * @return Result
     */
    @PostMapping("deleteCustomer")
    @ApiOperation(value = "删除客户列表")
    public Result deleteCustomer(@RequestParam("ids") String ids) {
        try {
            systemService.deleteCustomer(ids);
            return new Result(true, StatusCode.OK, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "删除失败");
        }
    }

    /**
     * 添加仓库
     *
     * @param warehouse
     * @param flag
     * @return
     */
    @PostMapping("addWarehouse")
    @ApiOperation(value = "添加仓库")
    public Result addWarehouse(Warehouse warehouse, @RequestParam("flag") String flag) {
        try {
            if (addFlag.equals(flag)) {
                warehouse.setWarehouse_status("0");
                systemService.addWarehouse(warehouse);
            } else {
                systemService.editWarehouse(warehouse);
            }
            return new Result(true, StatusCode.OK, "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "添加失败");
        }
    }

    /**
     * 获取仓库列表
     *
     * @param shop_id
     * @param warehouse_name
     * @param warehouse_type
     * @return
     */
    @PostMapping("getWarehouse")
    @ApiOperation(value = "获取仓库列表")
    public Result getWarehouse(@RequestParam("shop_id") Integer shop_id, @RequestParam("warehouse_name") String warehouse_name, @RequestParam("warehouse_type") String warehouse_type) {
        try {
            List<Warehouse> warehouses = systemService.getWarehouse(shop_id, warehouse_name, warehouse_type);
            return new Result(true, StatusCode.OK, "获取成功", warehouses);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "获取失败");
        }
    }

    /**
     * 删除仓库
     *
     * @param ids
     */
    @PostMapping("deleteWarehouse")
    @ApiOperation(value = "删除仓库")
    public Result deleteWarehouse(@RequestParam("ids") String ids) {
        try {
            systemService.deleteWarehouse(ids);
            return new Result(true, StatusCode.OK, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "删除失败");
        }
    }

    /**
     * 获取过期客户
     *
     * @param shop_id
     * @return
     */
    @PostMapping("getCustomerWarn")
    @ApiOperation(value = "获取过期客户")
    public Result getCustomerWarn(@RequestParam("shop_id") Integer shop_id) {
        try {
            List<Customer> customers = systemService.getCustomerWarn(shop_id);
            return new Result(true, StatusCode.OK, "查询成功", customers);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "查询失败");
        }
    }

    @GetMapping("/exportCustomerWarn")
    @ApiOperation(value = "客户证件预警表")
    public void exportCustomerWarn(Integer shop_id, HttpServletResponse response) throws IOException {
        try {
            List<Customer> customers = systemService.getCustomerWarn(shop_id);
            HSSFWorkbook wb = new HSSFWorkbook();
// 根据页面index 获取sheet页
            HSSFSheet sheet = wb.createSheet("客户证件预警表");
            int i = 0;
            HSSFRow row = sheet.createRow(0);
            row.createCell(0).setCellValue("客户代码");
            row.createCell(1).setCellValue("客户名称");
            row.createCell(2).setCellValue("营业执照到期日");
            row.createCell(3).setCellValue("GMP证书到期日");
            row.createCell(4).setCellValue("经营许可证到期日");
            row.createCell(5).setCellValue("组织代码证到期日");
            for (Customer root : customers) {
                row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(root.getCustomer_num());
                row.createCell(1).setCellValue(root.getCustomer_name());
                row.createCell(2).setCellValue(root.getBusLicence_date());
                row.createCell(3).setCellValue(root.getGMP_date());
                row.createCell(4).setCellValue(root.getLicence_date());
                row.createCell(5).setCellValue(root.getCode_date());
                i++;
            }
// 输出Excel文件
            OutputStream output = response.getOutputStream();
            response.reset();
// 设置文件头
            response.setHeader("Content-Disposition",
                    "attchement;filename=" + new String("客户证件预警表.xls".getBytes("gb2312"), "ISO8859-1"));
            response.setContentType("application/msexcel");
            wb.write(output);
            wb.close();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取过期代理商
     *
     * @param shop_id
     * @return
     */
    @PostMapping("getSupplierWarn")
    @ApiOperation(value = "获取过期供应商")
    public Result getSupplierWarn(@RequestParam("shop_id") Integer shop_id) {
        try {
            List<Supplier> suppliers = systemService.getSupplierWarn(shop_id);
            return new Result(true, StatusCode.OK, "查询成功", suppliers);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "查询失败");
        }
    }

    @GetMapping("/exportSupplierWarn")
    @ApiOperation(value = "供应商证件预警表")
    public void exportSupplierWarn(Integer shop_id, HttpServletResponse response) throws IOException {
        try {
            List<Supplier> suppliers = systemService.getSupplierWarn(shop_id);
            HSSFWorkbook wb = new HSSFWorkbook();
// 根据页面index 获取sheet页
            HSSFSheet sheet = wb.createSheet("供应商证件预警表");
            int i = 0;
            HSSFRow row = sheet.createRow(0);
            row.createCell(0).setCellValue("供应商代码");
            row.createCell(1).setCellValue("供应商名称");
            row.createCell(2).setCellValue("营业执照到期日");
            row.createCell(3).setCellValue("GMP证书到期日");
            row.createCell(4).setCellValue("经营许可证到期日");
            row.createCell(5).setCellValue("组织代码证到期日");
            for (Supplier root : suppliers) {
                row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(root.getSupplier_num());
                row.createCell(1).setCellValue(root.getSupplier_name());
                row.createCell(2).setCellValue(root.getBusLicence_date());
                row.createCell(3).setCellValue(root.getGMP_date());
                row.createCell(4).setCellValue(root.getLicence_date());
                row.createCell(5).setCellValue(root.getCode_date());
                i++;
            }
// 输出Excel文件
            OutputStream output = response.getOutputStream();
            response.reset();
// 设置文件头
            response.setHeader("Content-Disposition",
                    "attchement;filename=" + new String("供应商证件预警表.xls".getBytes("gb2312"), "ISO8859-1"));
            response.setContentType("application/msexcel");
            wb.write(output);
            wb.close();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}